package com.liujit.standard.basis.admin.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liujit.standard.basis.admin.mapper.SysMenuMapper;
import com.liujit.standard.basis.admin.mapper.SysRoleMenuMapper;
import com.liujit.standard.basis.admin.model.SysMenu;
import com.liujit.standard.basis.admin.service.SysMenuService;
import com.liujit.standard.basis.core.exception.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description 系统菜单Service实现类
 * @Author LiuJun
 * @Date 2021-03-26 09:15:51
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Resource
    private SysMenuMapper sysMenuMapper;

    @Resource
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean del(Long id) {
        // 查询是否存在子集
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("pid", id);
        List<SysMenu> list = sysMenuMapper.selectList(wrapper);
        if (list.size() > 0) {
            throw new BusinessException("请先清除子集");
        }
        // 删除角色菜单
        wrapper = new QueryWrapper();
        wrapper.eq("menu_id", id);
        sysRoleMenuMapper.delete(wrapper);
        Integer res = sysMenuMapper.deleteById(id);
        if (res == 1) {
            return true;
        }
        return false;
    }

    @Override
    public List<Tree<Long>> getTree() {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.ne("menu_type", 3);
        List<SysMenu> list = sysMenuMapper.selectList(wrapper);

        // 配置树
        TreeNodeConfig config = new TreeNodeConfig();
        config.setParentIdKey("pid");
        config.setNameKey("title");
        config.setWeightKey("seq");
        // 排序字段
        return TreeUtil.build(list, 0L, config, (object, tree) -> {
            tree.putExtra("id", object.getId());
            tree.putExtra("pid", object.getPid());
            tree.putExtra("title", object.getTitle());
            tree.putExtra("menuType", object.getMenuType());
        });
    }
}
